package server.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import server.demo.dto.ApiResponse;
import server.demo.dto.CreateTrainRequest;
import server.demo.dto.TrainDTO;
import server.demo.dto.TransferRouteDTO;
import server.demo.dto.TransferSearchRequest;
import server.demo.service.TrainService;

import jakarta.validation.Valid;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/v1/trains")
@CrossOrigin(origins = "*")
public class TrainController {
    
    @Autowired
    private TrainService trainService;
    
    @GetMapping
    public ApiResponse<List<TrainDTO>> getAllTrains() {
        try {
            List<TrainDTO> trains = trainService.getAllTrains();
            return ApiResponse.success(trains);
        } catch (Exception e) {
            return ApiResponse.error("获取车次列表失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/{id}")
    public ApiResponse<TrainDTO> getTrainById(@PathVariable Long id) {
        try {
            Optional<TrainDTO> train = trainService.getTrainById(id);
            if (train.isPresent()) {
                return ApiResponse.success(train.get());
            } else {
                return ApiResponse.error("车次不存在");
            }
        } catch (Exception e) {
            return ApiResponse.error("获取车次信息失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/number/{trainNumber}")
    public ApiResponse<TrainDTO> getTrainByNumber(@PathVariable String trainNumber) {
        try {
            Optional<TrainDTO> train = trainService.getTrainByNumber(trainNumber);
            if (train.isPresent()) {
                return ApiResponse.success(train.get());
            } else {
                return ApiResponse.error("车次不存在");
            }
        } catch (Exception e) {
            return ApiResponse.error("获取车次信息失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/search")
    public ApiResponse<List<TrainDTO>> searchTrains(
            @RequestParam Long startStationId,
            @RequestParam Long endStationId,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate travelDate) {
        try {
            List<TrainDTO> trains = trainService.searchTrains(startStationId, endStationId, travelDate);
            return ApiResponse.success(trains);
        } catch (Exception e) {
            return ApiResponse.error("搜索车次失败: " + e.getMessage());
        }
    }
    
    @PostMapping
    public ApiResponse<TrainDTO> createTrain(@Valid @RequestBody CreateTrainRequest request) {
        try {
            TrainDTO train = trainService.createTrain(request);
            return ApiResponse.success("车次创建成功", train);
        } catch (Exception e) {
            return ApiResponse.error("创建车次失败: " + e.getMessage());
        }
    }
    
    @PutMapping("/{id}")
    public ApiResponse<TrainDTO> updateTrain(@PathVariable Long id, @Valid @RequestBody CreateTrainRequest request) {
        try {
            TrainDTO train = trainService.updateTrain(id, request);
            return ApiResponse.success("车次更新成功", train);
        } catch (Exception e) {
            return ApiResponse.error("更新车次失败: " + e.getMessage());
        }
    }
    
    @PutMapping("/{id}/cancel")
    public ApiResponse<Void> cancelTrain(@PathVariable Long id) {
        try {
            trainService.cancelTrain(id);
            return ApiResponse.success("车次已取消", null);
        } catch (Exception e) {
            return ApiResponse.error("取消车次失败: " + e.getMessage());
        }
    }
    
    @DeleteMapping("/{id}")
    public ApiResponse<Void> deleteTrain(@PathVariable Long id) {
        try {
            trainService.deleteTrain(id);
            return ApiResponse.success("车次删除成功", null);
        } catch (Exception e) {
            return ApiResponse.error("删除车次失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/transfer")
    public ApiResponse<List<TransferRouteDTO>> searchTransferRoutes(
            @RequestParam Long startStationId,
            @RequestParam Long endStationId,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate travelDate,
            @RequestParam(defaultValue = "120") Integer maxTransferWait) {
        try {
            TransferSearchRequest request = new TransferSearchRequest(startStationId, endStationId, travelDate);
            request.setMaxTransferWait(maxTransferWait);
            
            List<TransferRouteDTO> routes = trainService.searchTransferRoutes(request);
            return ApiResponse.success(routes);
        } catch (Exception e) {
            return ApiResponse.error("查询换乘路线失败: " + e.getMessage());
        }
    }
    
    @PostMapping("/transfer")
    public ApiResponse<List<TransferRouteDTO>> searchTransferRoutesPost(@Valid @RequestBody TransferSearchRequest request) {
        try {
            List<TransferRouteDTO> routes = trainService.searchTransferRoutes(request);
            return ApiResponse.success(routes);
        } catch (Exception e) {
            return ApiResponse.error("查询换乘路线失败: " + e.getMessage());
        }
    }
}